package com.yiwei.zhh.manager;

import android.content.Context;
import android.graphics.ImageFormat;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.hardware.Camera.Parameters;
import android.util.Log;
import android.view.SurfaceHolder;

import com.yiwei.zhh.util.RBLog;
import com.yiwei.zhh.util.Util;

import java.io.IOException;
import java.util.List;

public class CameraManager {
    private static final String TAG = CameraManager.class.getName();
    private AutoFocusManager autoFocusManager;
    private Camera camera;
    private boolean initialized;
    private Context mContext;
    private Parameters parameters;
    private boolean previewing;
    private int requestedCameraId = -1;
    private int type = 0;
    private int pWidth, pHeigh, picWidth, picHeigh, pWidth2, pHeigh2, picWidth2, picHeigh2 = 0;
    private int newParam = 90;

    public CameraManager(Context paramContext, int paramInt) {
        this.mContext = paramContext;
        this.type = paramInt;
    }

    /**
     * 关闭camera
     */
    public synchronized void closeDriver() {
        Log.e(TAG, "closeDriver");
        if (camera != null) {
            camera.release();
            camera = null;
        }
    }


    /**
     * camera是否打开
     *
     * @return camera是否打开
     */
    public synchronized boolean isOpen() {
        return camera != null;
    }


    /**
     * 关闭闪光灯
     */
    public synchronized void offLight() {
        Log.e(TAG, "offLight");
        if (camera != null) {
            parameters = camera.getParameters();
            parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);

            camera.setParameters(parameters);
        }
    }

    /**
     * 打开摄像头
     *
     * @param cameraId 摄像头id
     * @return Camera
     */
    public Camera open(int cameraId) {
        int numCameras = Camera.getNumberOfCameras();
        if (numCameras == 0) {
            Log.e(TAG, "No cameras!");
            return null;
        }
        boolean explicitRequest = cameraId >= 0;
        if (!explicitRequest) {
            // Select a camera if no explicit camera requested
            int index = 0;
            while (index < numCameras) {
                Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
                Camera.getCameraInfo(index, cameraInfo);

                if (cameraInfo.facing == CameraInfo.CAMERA_FACING_BACK && type == 1) {
                    break;
                } else if (cameraInfo.facing == CameraInfo.CAMERA_FACING_FRONT) {
                    break;
                }

                index++;
            }
            cameraId = index;
        }
        Camera camera;
        if (cameraId < numCameras) {
            Log.e(TAG, "Opening camera #" + cameraId);
            camera = Camera.open(cameraId);
        } else {
            if (explicitRequest) {
                Log.e(TAG, "Requested camera does not exist: " + cameraId);
                camera = null;
            } else {
                Log.e(TAG, "No camera facing back; returning camera #0");
                camera = Camera.open(0);
            }
        }
        return camera;
    }


    /**
     * 打开camera
     *
     * @param holder SurfaceHolder
     * @throws IOException IOException
     */
    public synchronized void openDriver(SurfaceHolder holder)
            throws IOException {
        Log.e(TAG, "openDriver");
        Camera theCamera = camera;
        if (theCamera == null) {
            theCamera = open(requestedCameraId);
            if (theCamera == null) {
                throw new IOException();
            }
            camera = theCamera;
        }
        theCamera.setPreviewDisplay(holder);


//        int sWidth = Util.getScreenWidth(mContext);
//        int sHeight = Util.getScreenHeight(mContext);
        int bStatusHeight = Util.getBottomStatusHeight(mContext);

//        ToastUtil.makeText(mContext, "开始初始化参数", Toast.LENGTH_LONG).show();

//        Log.i(" -----------   ", sWidth + "     " + sHeight + "         " + bStatusHeight);

        List<Camera.Size> pictureSizes = camera.getParameters().getSupportedPictureSizes();
        setPicSize(pictureSizes);

        RBLog.i("", "\n\n\n\n\n");

        List<Camera.Size> previewSizes = camera.getParameters().getSupportedPreviewSizes();
        setPreviewSize(previewSizes);


//        ToastUtil.makeText(mContext, pWidth2 + "  " + pWidth2 + "    " + pHeigh2 + "     " + pHeigh2, Toast.LENGTH_LONG).show();


//        RBLog.i("默认尺寸------------", "pWidth2:-- " + pWidth2 + " pHeigh2:-- " + pHeigh2 + "     picWidth2:--" + picWidth2 + "    picHeigh2:--" + picHeigh2);

        if (!initialized) {
            initialized = true;
            parameters = camera.getParameters();
            if (pHeigh < 600 || picHeigh < 600)
                parameters.setPreviewSize(pWidth2, pHeigh2); //当小于600时使用最大尺寸
            else
                parameters.setPreviewSize(pWidth, pHeigh);

            if (picHeigh < 600 || pHeigh < 600)
                parameters.setPictureSize(picWidth2, picHeigh2); //当小于600时使用最大尺寸
            else
                parameters.setPictureSize(picWidth, picHeigh);
            parameters.setPictureFormat(ImageFormat.JPEG);
            parameters.setJpegQuality(100);
            theCamera.setParameters(parameters);
//            Log.i(TAG + "initCamera------------", "   设置参数成功");

//            ToastUtil.makeText(mContext,pWidth2+"  "+pHeigh2+"    "+picWidth2+"     "+picHeigh2, Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 设置照片尺寸
     *
     * @param pictureSizes
     */
    private void setPicSize(List<Camera.Size> pictureSizes) {
        int sWidth = Util.getScreenWidth(mContext);
        int sHeight = Util.getScreenHeight(mContext);
        if (pictureSizes.get(pictureSizes.size() - 1).width > pictureSizes.get(0).width) {
            for (int i = pictureSizes.size() - 1; i > 0; i--) {
                Camera.Size picSize = pictureSizes.get(i);
                if (Math.abs(sWidth * picSize.height / sHeight - picSize.width) < 200 || Math.abs(sWidth * picSize.width / sHeight - picSize.height) < 200) {
                    if (picWidth == 0 && picHeigh == 0) {
                        picWidth = picSize.width;
                        picHeigh = picSize.height;
                        RBLog.i("PictureSize:------- ", picWidth + "     " + picHeigh);
                    }
                }
                if (i == pictureSizes.size() - 1) {  //最大尺寸
                    picWidth2 = picSize.width;
                    picHeigh2 = picSize.height;
                }
                RBLog.i("1-----------", "picWidth:--" + picSize.width + "  picHeigh:--" + picSize.height + "       " + Math.abs(sWidth * picSize.height / sHeight - picSize.width) + "     picWidth2:--" + picWidth2 + "    picHeigh2:--" + picHeigh2);
            }
        } else {
            for (int i = 0; i < pictureSizes.size(); i++) {
                Camera.Size picSize = pictureSizes.get(i);
                if (Math.abs(sWidth * picSize.height / sHeight - picSize.width) < 200 || Math.abs(sWidth * picSize.width / sHeight - picSize.height) < 200) {
                    if (picWidth == 0 && picHeigh == 0) {
                        picWidth = picSize.width;
                        picHeigh = picSize.height;
                        RBLog.i("PictureSize:------- ", picWidth + "     " + picHeigh);
                    }
                }
                if (i == 0) {  //最大尺寸
                    picWidth2 = picSize.width;
                    picHeigh2 = picSize.height;
                }
                RBLog.i("1-----------", "picWidth:--" + picSize.width + "  picHeigh:--" + picSize.height + "       " + Math.abs(sWidth * picSize.height / sHeight - picSize.width) + "     picWidth2:--" + picWidth2 + "    picHeigh2:--" + picHeigh2);
            }
        }
    }

    /**
     * 设置预览照片尺寸
     *
     * @param previewSizes
     */
    private void setPreviewSize(List<Camera.Size> previewSizes) {
        int sWidth = Util.getScreenWidth(mContext);
        int sHeight = Util.getScreenHeight(mContext);
        if (previewSizes.get(previewSizes.size() - 1).width > previewSizes.get(0).width) {
            for (int i = previewSizes.size() - 1; i > 0; i--) {
                Camera.Size pSize = previewSizes.get(i);
                if (Math.abs(sWidth * pSize.height / sHeight - pSize.width) < 200 || Math.abs(sWidth * pSize.width / sHeight - pSize.height) < 200) {
                    if (pWidth == 0 && pHeigh == 0) {
                        pWidth = pSize.width;
                        pHeigh = pSize.height;
                        RBLog.i("PreviewSize:------- ", pWidth + "     " + pHeigh);
                    }
                }
                if (i == previewSizes.size() - 1) {  //最大尺寸
                    pWidth2 = pSize.width;
                    pHeigh2 = pSize.height;
                }
                RBLog.i("2------------", "pWidth:-- " + pSize.width + " pHeigh:-- " + pSize.height + "     pWidth2:--" + pWidth2 + "    pHeigh2:--" + pHeigh2);
            }
        } else {
            for (int i = 0; i < previewSizes.size(); i++) {
                Camera.Size pSize = previewSizes.get(i);
                if (Math.abs(sWidth * pSize.height / sHeight - pSize.width) < 200 || Math.abs(sWidth * pSize.width / sHeight - pSize.height) < 200) {
                    if (pWidth == 0 && pHeigh == 0) {
                        pWidth = pSize.width;
                        pHeigh = pSize.height;
                        RBLog.i("PreviewSize:------- ", pWidth + "     " + pHeigh);
                    }
                }
                if (i == 0) {  //最大尺寸
                    pWidth2 = pSize.width;
                    pHeigh2 = pSize.height;
                }
                RBLog.i("2------------", "pWidth:-- " + pSize.width + " pHeigh:-- " + pSize.height + "     pWidth2:--" + pWidth2 + "    pHeigh2:--" + pHeigh2);
            }
        }
    }

    /**
     * 打开闪光灯
     */
    public synchronized void openLight() {
        Log.e(TAG, "openLight");
        if (camera != null) {
            parameters = camera.getParameters();
            parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
            camera.setParameters(parameters);
        }
    }


    /**
     * 开始预览
     */
    public synchronized void startPreview() {
        Log.e(TAG, "startPreview");
        Camera theCamera = camera;
        if (this.type == 0)
            theCamera.setDisplayOrientation(90);


        if (theCamera != null && !previewing) {
            theCamera.startPreview();
            previewing = true;
            autoFocusManager = new AutoFocusManager(camera);
        }
    }

    /**
     * 设置摄像头方向
     *
     * @param param
     */
    public void setOrientation(int param) {
        newParam = newParam + param;
        if (newParam >= 360) newParam = 90;
        if (this.type == 0)
            camera.setDisplayOrientation(newParam);
    }


    /**
     * 关闭预览
     */
    public synchronized void stopPreview() {
        Log.e(TAG, "stopPreview");
        if (autoFocusManager != null) {
            autoFocusManager.stop();
            autoFocusManager = null;
        }
        if (camera != null && previewing) {
            camera.stopPreview();
            previewing = false;
        }
    }

    /**
     * 拍照
     *
     * @param shutter ShutterCallback
     * @param raw     PictureCallback
     * @param jpeg    PictureCallback
     */
    public synchronized void takePicture(final Camera.ShutterCallback shutter, final Camera.PictureCallback raw,
                                         final Camera.PictureCallback jpeg) {

        if (camera != null)
            camera.takePicture(shutter, raw, jpeg);

    }
}
